<template>
  <div class="screen-recorder">
    <h2>屏幕录制</h2>

    <div class="source-selector">
      <label for="sourceSelect">选择录制源：</label>
      <el-select
        id="sourceSelect"
        v-model="selectedSourceId"
        @change="handleSourceChange"
        clearable="true"
        placeholder="请选择屏幕或窗口"
      >
        <el-option v-for="source in sources" :key="source.id" :value="source.id">
          {{ source.name }}
        </el-option>
      </el-select>
    </div>

    <div class="preview-container">
      <video
        ref="previewVideo"
        autoplay
        :class="{ recording: isRecording, paused: isPaused }"
      ></video>
      <div v-if="isRecording" class="recording-indicator"></div>
      <div v-if="isPaused" class="paused-indicator">已暂停</div>
    </div>

    <div class="controls">
      <el-button
        class="start-btn"
        @click="startRecording"
        :disabled="!selectedSourceId || isRecording"
      >
        <i class="icon-play"></i> 开始录制
      </el-button>

      <el-button class="pause-btn" @click="togglePauseRecording" :disabled="!isRecording">
        <i v-if="!isPaused" class="icon-pause"></i>
        <i v-if="isPaused" class="icon-play"></i>
        {{ isPaused ? '继续' : '暂停' }}
      </el-button>

      <el-button class="stop-btn" @click="stopRecording" :disabled="!isRecording">
        <i class="icon-stop"></i> 停止录制
      </el-button>
    </div>

    <div class="status" :class="statusType">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 状态变量
const sources = ref([])
const selectedSourceId = ref('')
const previewVideo = ref(null)
const isRecording = ref(false)
const isPaused = ref(false)
const currentRecorderId = ref(null)
const statusMessage = ref('就绪')
const statusType = ref('info')
const mediaStream = ref(null)

// 初始化：加载可用的录制源
onMounted(async () => {
  try {
    statusMessage.value = '正在加载可用的录制源...'

    const result = await window.electronAPI.getSources()
    if (result.success) {
      sources.value = result.sources
      statusMessage.value = '请选择一个录制源'
    } else {
      statusMessage.value = `加载失败: ${result.error}`
      statusType.value = 'error'
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`
    statusType.value = 'error'
  }
})

// 清理资源
onUnmounted(() => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => track.stop())
  }
})

// 处理录制源变更
const handleSourceChange = async () => {
  if (!selectedSourceId.value) {
    // 停止预览
    if (mediaStream.value) {
      mediaStream.value.getTracks().forEach((track) => track.stop())
      mediaStream.value = null
    }
    if (previewVideo.value) {
      previewVideo.value.srcObject = null
    }
    statusMessage.value = '请选择一个录制源'
    return
  }

  try {
    statusMessage.value = '正在准备预览...'

    // 停止之前的流
    if (mediaStream.value) {
      mediaStream.value.getTracks().forEach((track) => track.stop())
    }

    // 创建新的媒体流
    mediaStream.value = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: {
        mandatory: {
          chromeMediaSource: 'desktop', // 告知使用桌面源
          chromeMediaSourceId: selectedSourceId.value
        }
      }
    })

    // 设置预览
    previewVideo.value.srcObject = mediaStream.value
    statusMessage.value = '预览已准备好，点击"开始录制"按钮开始'
    statusType.value = 'info'
  } catch (error) {
    statusMessage.value = `预览失败: ${error.message}`
    statusType.value = 'error'
    console.error('预览错误:', error)
  }
}

// 开始录制
const startRecording = async () => {
  if (!selectedSourceId.value) return

  try {
    statusMessage.value = '正在开始录制...'

    const result = await window.electronAPI.startRecording({
      sourceId: selectedSourceId.value,
      audio: false,
      videoFormat: 'webm'
    })

    if (result.success) {
      currentRecorderId.value = result.recorderId
      isRecording.value = true
      isPaused.value = false
      statusMessage.value = '正在录制...'
      statusType.value = 'recording'
    } else {
      statusMessage.value = `录制失败: ${result.error}`
      statusType.value = 'error'
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`
    statusType.value = 'error'
    console.error('录制错误:', error)
  }
}

// 暂停/继续录制
const togglePauseRecording = async () => {
  if (!currentRecorderId.value) return

  try {
    if (!isPaused.value) {
      // 暂停录制
      const result = await window.electronAPI.pauseRecording(currentRecorderId.value)
      if (result.success) {
        isPaused.value = true
        statusMessage.value = '录制已暂停'
        statusType.value = 'paused'
      } else {
        statusMessage.value = `暂停失败: ${result.error}`
        statusType.value = 'error'
      }
    } else {
      // 继续录制
      const result = await window.electronAPI.resumeRecording(currentRecorderId.value)
      if (result.success) {
        isPaused.value = false
        statusMessage.value = '正在录制...'
        statusType.value = 'recording'
      } else {
        statusMessage.value = `继续失败: ${result.error}`
        statusType.value = 'error'
      }
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`
    statusType.value = 'error'
    console.error('录制控制错误:', error)
  }
}

// 停止录制
const stopRecording = async () => {
  if (!currentRecorderId.value) return

  try {
    statusMessage.value = '正在处理录制文件...'

    const result = await window.electronAPI.stopRecording(currentRecorderId.value)

    if (result.success) {
      isRecording.value = false
      isPaused.value = false
      currentRecorderId.value = null
      statusMessage.value = `录制已保存至: ${result.path}`
      statusType.value = 'success'
    } else {
      statusMessage.value = `停止录制失败: ${result.error}`
      statusType.value = 'error'
    }
  } catch (error) {
    statusMessage.value = `发生错误: ${error.message}`
    statusType.value = 'error'
    console.error('停止录制错误:', error)
  }
}
</script>

<style scoped lang="scss">
.screen-recorder {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  color: #2c3e50;
  margin-top: 0;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #eee;
}

.source-selector {
  margin: 1rem 0;

  label {
    display: block;
    margin-bottom: 0.5rem;
    color: #34495e;
    font-weight: 500;
  }

  select {
    width: 100%;
    padding: 0.7rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    background-color: white;
  }
}

.preview-container {
  width: 100%;
  height: 300px;
  background-color: #000;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  margin: 1.5rem 0;

  video {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .recording-indicator {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 12px;
    height: 12px;
    background-color: #e74c3c;
    border-radius: 50%;
    animation: pulse 1.5s infinite;
  }

  .paused-indicator {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    font-weight: bold;
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.4;
  }
  100% {
    opacity: 1;
  }
}

.controls {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
  flex-wrap: wrap;

  button {
    padding: 0.7rem 1.2rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.2s;

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }

    &:not(:disabled):hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
  }

  .start-btn {
    background-color: #2ecc71;
    color: white;
  }

  .pause-btn {
    background-color: #f39c12;
    color: white;
  }

  .stop-btn {
    background-color: #e74c3c;
    color: white;
  }

  .icon-play::before {
    content: '▶';
  }

  .icon-pause::before {
    content: '⏸';
  }

  .icon-stop::before {
    content: '■';
  }
}

.status {
  padding: 0.8rem;
  border-radius: 4px;
  margin-top: 0.5rem;
  font-size: 0.95rem;

  &.info {
    background-color: #ecf0f1;
    color: #34495e;
  }

  &.recording {
    background-color: #ffebee;
    color: #c0392b;
  }

  &.paused {
    background-color: #fff3e0;
    color: #e67e22;
  }

  &.success {
    background-color: #e8f5e9;
    color: #2e7d32;
  }

  &.error {
    background-color: #ffebee;
    color: #c62828;
  }
}
</style>
